<template>
  <div class="accessory-management-view">
    <!-- 搜索区域 -->
    <div class="search-bar">
      <div class="search-area">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入配件名称"
          prefix-icon="el-icon-search"
          size="small"
          style="width: 250px;"
          clearable
          @keyup.enter.native="handleSearch"
        ></el-input>
        <el-button type="primary" size="small" style="margin-left: 10px;" @click="handleSearch">搜索</el-button>
        <el-button size="small" @click="resetSearch">重置</el-button>
      </div>
      <div class="operation-area">
        <el-button type="primary" size="small" @click="handleAdd">新增配件</el-button>
      </div>
    </div>

    <!-- 配件列表表格 -->
    <el-table 
      :data="filteredAccessoryList" 
      style="width: 100%; margin-top: 20px;" 
      border 
      v-loading="loading"
    >
      <el-table-column label="序号" width="60px" align="center">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="id" label="配件ID" width="80px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="accessory_name" label="配件名称" min-width="200px" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.accessory_name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="180px" align="center">
        <template slot-scope="scope">
          <span>{{ formatDate(scope.row.create_time) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" width="180px" align="center">
        <template slot-scope="scope">
          <span>{{ formatDate(scope.row.update_time) }}</span>
        </template>
      </el-table-column>
      
      <!-- 操作列 -->
      <el-table-column label="操作" width="180px" align="center">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="text" size="small" style="color: #F56C6C;" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      >
      </el-pagination>
    </div>

    <!-- 新增/编辑配件弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false"
      center
    >
      <el-form :model="form" :rules="formRules" ref="form" label-width="100px">
        <el-form-item label="配件名称" prop="accessory_name">
          <el-input 
            v-model="form.accessory_name" 
            placeholder="请输入配件名称"
            maxlength="50"
            show-word-limit
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm" :loading="submitLoading">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAccessoryList, addAccessory, updateAccessory, deleteAccessory } from '@/api/contract';
import { checkToken, handleTokenExpired, checkTokenFromError } from '@/utils/auth';

export default {
  name: 'AccessoryManagementView',
  data() {
    return {
      // 搜索相关
      searchKeyword: '',
      
      // 表格数据
      accessoryList: [],
      loading: false,
      
      // 分页相关
      currentPage: 1,
      pageSize: 10,
      total: 0,

      // 弹窗相关
      dialogVisible: false,
      dialogTitle: '新增配件',
      isEdit: false,
      submitLoading: false,
      
      // 表单数据
      form: {
        id: '',
        accessory_name: ''
      },
      
      // 表单验证规则
      formRules: {
        accessory_name: [
          { required: true, message: '请输入配件名称', trigger: 'blur' },
          { min: 1, max: 50, message: '配件名称长度在 1 到 50 个字符', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    filteredAccessoryList() {
      return this.accessoryList;
    }
  },
  methods: {
    // 获取配件列表
    async fetchAccessoryList() {
      this.loading = true;
      try {
        // 检查token是否存在
        if (!checkToken()) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
          return;
        }

        const params = {
          page: this.currentPage,
          pageSize: this.pageSize,
          keyword: this.searchKeyword
        };
        
        const response = await getAccessoryList(params);
        
        if (response.data.code === 1) {
          this.accessoryList = response.data.data.data || [];
          this.total = response.data.data.total || 0;
        } else {
          this.$message.error(response.data.msg || '获取配件列表失败');
        }
      } catch (error) {
        console.error('获取配件列表失败:', error);
        if (checkTokenFromError(error)) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
        } else {
          this.$message.error('获取配件列表失败');
        }
      } finally {
        this.loading = false;
      }
    },
    
    // 搜索
    handleSearch() {
      this.currentPage = 1;
      this.fetchAccessoryList();
    },
    
    // 重置搜索
    resetSearch() {
      this.searchKeyword = '';
      this.currentPage = 1;
      this.fetchAccessoryList();
    },
    
    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchAccessoryList();
    },
    
    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchAccessoryList();
    },

    // 新增配件
    handleAdd() {
      this.dialogTitle = '新增配件';
      this.isEdit = false;
      this.form = {
        id: '',
        accessory_name: ''
      };
      this.dialogVisible = true;
      // 清除表单验证
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate();
      });
    },

    // 编辑配件
    handleEdit(row) {
      this.dialogTitle = '编辑配件';
      this.isEdit = true;
      
      this.form = {
        id: row.id,
        accessory_name: row.accessory_name,
      };
      this.dialogVisible = true;
      // 清除表单验证
      this.$nextTick(() => {
        this.$refs.form && this.$refs.form.clearValidate();
      });
    },

    // 删除配件
    async handleDelete(row) {
      try {
        await this.$confirm(`确定要删除配件"${row.accessory_name}"吗？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        // 检查token是否存在
        if (!checkToken()) {
          this.$message.error('登录已过期，请重新登录');
          handleTokenExpired();
          return;
        }
        
        const response = await deleteAccessory(row.id);
        
        if (response.data.code === 1) {
          this.$message.success('删除配件成功');
          this.fetchAccessoryList();
        } else {
          this.$message.error(response.data.msg || '删除配件失败');
        }
      } catch (error) {
        if (error === 'cancel') {
          this.$message.info('已取消删除');
        } else {
          console.error('删除配件失败:', error);
          if (checkTokenFromError(error)) {
            this.$message.error('登录已过期，请重新登录');
            handleTokenExpired();
          } else {
            this.$message.error('删除配件失败');
          }
        }
      }
    },

    // 提交表单
    async submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          this.submitLoading = true;
          try {
            // 检查token是否存在
            if (!checkToken()) {
              this.$message.error('登录已过期，请重新登录');
              handleTokenExpired();
              return;
            }

            const submitData = {
              accessory_name: this.form.accessory_name.trim(),
            };

            let response;
            if (this.isEdit) {
              submitData.id = this.form.id;
              response = await updateAccessory(submitData);
            } else {
              response = await addAccessory(submitData);
            }

            if (response.data.code === 1) {
              this.$message.success(this.isEdit ? '编辑配件成功' : '新增配件成功');
              this.dialogVisible = false;
              this.fetchAccessoryList();
            } else {
              this.$message.error(response.data.msg || (this.isEdit ? '编辑配件失败' : '新增配件失败'));
            }
          } catch (error) {
            console.error('提交配件信息失败:', error);
            if (checkTokenFromError(error)) {
              this.$message.error('登录已过期，请重新登录');
              handleTokenExpired();
            } else {
              this.$message.error('操作失败');
            }
          } finally {
            this.submitLoading = false;
          }
        }
      });
    },

    // 格式化日期
    formatDate(timestamp) {
      if (!timestamp) return '-';
      const date = new Date(timestamp * 1000);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      const seconds = String(date.getSeconds()).padStart(2, '0');
      
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
  },
  
  created() {
    this.fetchAccessoryList();
  }
};
</script>

<style scoped>
.accessory-management-view {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 60px);
  box-sizing: border-box;
}

.search-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-area {
  display: flex;
  align-items: center;
}

.operation-area {
  display: flex;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.dialog-footer {
  text-align: right;
}

/* 表格样式 */
.el-table {
  border: 1px solid #EBEEF5;
}

.el-table th {
  background-color: #f5f7fa !important;
  color: #606266;
}

.el-table td, .el-table th {
  border-bottom: 1px solid #EBEEF5;
  border-right: 1px solid #EBEEF5;
}

.el-table th:last-child,
.el-table td:last-child {
  border-right: none;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-bar {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .search-area {
    margin-bottom: 10px;
  }
  
  .operation-area {
    align-self: flex-end;
  }
}
</style> 